//app.js
const util = require('./utils/util.js')
const API = require('./utils/api.js')
App({
  
  getToken:function(){
    var _this = this;
    return new Promise(function(resolve,reject){
      wx.login({
        success:function(res){
          if(res.code){
            _this.globalData.code = res.code;
            wx.getUserInfo({
              withCredentials: true,
              lang: 'zh_CN',
              timeout:30000,
              success:function(userInfo){
                
                _this.globalData.UserRes = userInfo;
                _this.globalData.userInfo = userInfo;
                console.log("user==" + JSON.stringify(userInfo))
                userInfo.code = res.code
                
                API._login({
                  method: 'POST',//网络请求类型
                  data: {
                    "code": _this.globalData.code,
                    'fullUserInfo': _this.globalData.UserRes
                  },//参数
                  success: function (result) {
                    // console.log("result === " + JSON.stringify(result))
                    _this.globalData.userId = result.data.data.userInfo.id;
                    userInfo.token = result.data.data.token;
                    // console.log("return === " +JSON.stringify(result))
                    if (result.data.errno == 0) {
                      // 把token和UserId存储到storage里，方便其他页面调用
                      // console.log('登录返回错误码是：' + result.data.errno)
                      console.warn("登录状态：登陆成功")
                      _this.globalData.token = result.data.data.token;
                      _this.globalData.userId = result.data.data.userInfo.id;
                      // console.log("token == " + JSON.stringify(_this.globalData.token))
                      wx.setStorage({
                        key: 'token',
                        data: result.data.data.token,
                      })
                      wx.setStorage({
                        key: 'userId',
                        data: result.data.data.userInfo.id,
                      })
                      wx.setStorage({
                        key: 'userInfo',
                        data: result.data.data.userInfo,
                      })
                      var promiseRes = {
                        status: 200,
                        token: result.data.data.token,
                        userId: result.data.data.userInfo.id,
                        userInfo: result.data.data.userInfo
                      }
                      resolve(promiseRes);

                    }

                  },//请求成功的处理

                })
              },
              fail (info){
                console.warn(`获取用户信息失败！${info.errMsg}`)
                const code = res.code
                openSetting()
                function openSetting() {
                  if (wx.openSetting) {
                    util.alert('授权失败，请选择允许访问“用户信息”', () => {
                      wx.openSetting({
                        // todo: BUG解决
                        success: (res) => {
                          if (res.authSetting['scope.userInfo']) {
                            wx.getUserInfo({
                              success(info) {
                                info.code = code
                                resolve(info)
                              }
                            })
                          } else {
                            util.alert('授权失败，操作无法完成，请重试。')
                            reject(res)
                          }
                        },
                        fail: reject
                      })
                    })
                  } else {
                    util.alert('唤起授权窗口失败，请进入小程序列表，删除后重新访问并授权。')
                    reject(info)
                  }
                }
              }
            })
          }else{
            console.log('获取用户登录态失败！' + res.errMsg);
            var res = {
              status: 300,
              data: '错误'
            }
            reject('error');
          }
        }
      })
    })
  },


  onLaunch: function () {


    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    //清除storage里的日志
    wx.removeStorage({
      key: 'logs',
      success: function (res) {
      }
    })


  


  },




  

  
  globalData: {
    UserRes:'',
    userInfo: null,
    token: '',
    userId: '',
    code: '',
    msg: '',
  }
})

